const { token } = require("morgan");
const configs = require("./config");
const jwt = require('jsonwebtoken');
function authenticateToken(req, res, next) {
    const authHeader = req.headers['Authorization'];
    const accessToken = authHeader;
  
    if (!accessToken) {
        return res.status(400).json({ message: 'Access Token is missing',token:accessToken });
    }
  
    jwt.verify(accessToken, configs.token.SECRET_KEY, (err, user) => {
        if (err) {
            if (err.name === 'TokenExpiredError') {
  
              return res.status(401).json({ message: 'Access Token expired and no Refresh Token provided',token:accessToken  });
                // Access Token 过期，尝试使用 Refresh Token 刷新
                // const refreshToken = req.body.refreshToken || req.headers['x-refresh-token'];
                // if (!refreshToken) {
                //     return res.status(403).json({ message: 'Access Token expired and no Refresh Token provided' });
                // }
  
                // // 验证 Refresh Token
                // jwt.verify(refreshToken, REFRESH_SECRET_KEY, (err, user) => {
                //     if (err) {
                //         return res.status(403).json({ message: 'Refresh Token is invalid or expired' });
                //     }
  
                //     // 生成新的 Access Token
                //     const newAccessToken = jwt.sign({ userId: user.userId }, SECRET_KEY, { expiresIn: '15m' });
                //     res.setHeader('Authorization', `Bearer ${newAccessToken}`);
                //     req.user = user;
                //     next();
                // });
            } else {
                return res.status(403).json({ message: 'Access Token is invalid',token:accessToken });
            }
        } else {
            req.user = user;
            next();
        }
    });
  }
  module.exports = authenticateToken;